package cn.dt.org.service.impl;

import cn.dt.basic.service.impl.BaseServiceImpl;
import cn.dt.basic.util.PageList;
import cn.dt.org.domain.Department;
import cn.dt.org.mapper.DepartmentMapper;
import cn.dt.org.query.DepartmentQuery;
import cn.dt.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author:代伟
 * date:2022/6/1 13:31
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private  DepartmentMapper departmentMapper;

    /**
     * 无限级数
     * 1.查询所有
     * 2.获取所有第一级，只要没有父级就是第一级
     * 3.只要不是第一级都全部放到自己父级的children集合中。
     * @return
     */
    @Override
    public List<Department> queryTree() {
        //1.查询到所有的对象，
        List<Department> departments = departmentMapper.loadAll();
        Map<Long, Department> allDepts = new HashMap<>();
        for (Department department : departments) {
            allDepts.put(department.getId(),department);
        }
        ArrayList<Department> firstDepts = new ArrayList<>();
        for (Department temp : departments) {
            //2.获取所有无父类的第一级
            if(temp.getParent_id()==null){
                firstDepts.add(temp);
            }else{
                //3.只要不是第一级就放到父级的children对象中
                Department parent = allDepts.get(temp.getParent_id());
                if(parent!=null){
                    parent.getChildren().add(temp);
                }
            }
        }
        return firstDepts;
    }
}
